<template>
  <el-dialog title="执行诊断" :close-on-click-modal="false" :visible.sync="visible" ref="myDialog"
    class="JNPF-dialog JNPF-dialog_center" lock-scroll width="1024px" :modal-append-to-body="false" append-to-body>
    <el-row>
      <el-col :span="24" class="grid-content">
        <div class="hidden-area" style="margin-bottom: 8px;">
          <div class="input-group">
            <label class="input-label no-wrap-cell">故障描述:{{ faultinfo.fault_desc }}</label>
            <el-button style="margin-top: 8px;" type="primary" round @click="modelPipeline()">智能诊断编排</el-button>
          </div>
        </div>
        <el-table :data="step_list" style="width: 100%; max-height: 350px; overflow: auto;" ref="table">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="操作步骤" prop="step" width="100"></el-table-column>
          <el-table-column label="操作名称" prop="processor_name">
            <template slot-scope="scope">
              <div class="no-wrap-cell">{{ scope.row.processor_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作类型" prop="processor_type" width="150"></el-table-column>
          <el-table-column label="常用操作" prop="isoften" width="150"></el-table-column>
          <el-table-column label="进度" prop="progress" width="200">
            <template slot-scope="scope">
              <!-- <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)"></el-progress>
              <span class="progress-text">{{ formatProgress(scope.row.progress) }}%</span> -->
              <div class="progress-container">
                <el-progress :percentage="formatProgress(scope.row.progress)" class="progress-bar"></el-progress>
                <div v-if="scope.row.diagnosis_result == '通过'" class="status-icon success-icon">
                  <i class="el-icon-check"></i>
                </div>
                <div v-else-if="scope.row.diagnosis_result == '不通过'" class="status-icon exception-icon">
                  <i class="el-icon-close"></i>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="诊断结果" prop="diagnosis_result" show-overflow-tooltip></el-table-column>
          <el-table-column label="处置建议" prop="disposal_suggestions_tip" show-overflow-tooltip></el-table-column>
        </el-table>
        <el-button style="margin-top: 8px;" type="primary" round @click="executeDiag()">确认执行</el-button>
        <el-button style="margin-top: 8px;" type="warning" round  @click="stopExecution">停止执行</el-button>
        <!-- Hidden Area -->
        <div class="hidden-area" v-show="exeFinished" style="margin-top: 8px;">
          <div class="input-group">
            <label class="input-label no-wrap-cell">故障原因:</label>
            <el-input
              type="textarea"
              v-model="diagnosis_result"
              :rows="4"
              placeholder="输入故障原因"
            ></el-input>
          </div>
          <div class="input-group">
            <label class="input-label no-wrap-cell">处置建议:</label>
            <el-input
              type="textarea"
              v-model="disposal_suggestions"
              :rows="4"
              placeholder="输入处置建议"
            ></el-input>
            <!-- <el-button style="margin-top: 8px;" type="primary" round  @click="sendOrder">派发处置工单</el-button> -->
          </div>
          <!-- <div class="input-group">
            <label class="input-label no-wrap-cell">处置结果:</label>
            <el-input
              type="textarea"
              v-model="disposal_result"
              :rows="4"
              placeholder="输入处置结果"
            ></el-input>
          </div> -->
          <el-button style="margin-top: 8px;" type="primary" round  @click="sendOrder">派发处置工单</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { deepClone } from '@/utils'
export default {
  data() {
    return {
      visible: false,
      btnLoading: false,
      formData: {},
      faultinfo:{},
      init_step_list:[],
      step_list:[],
      task_insert_params:{},
      exeCount:0,
      exeFinishedCount:0,
      exeFinished:false,
      running:false,
      diagnosis_result:'',
      disposal_suggestions:'',
      disposal_result:'',
      failItem:null,
      executionTimeoutList:[]
    }
  },
  methods: {
    init(formData) {
      if (!formData) return
      this.visible = true
      this.formData = formData
      this.exeFinishedCount = 0;
      this.exeCount = 0;
      this.exeFinished = false;
      this.failItem = null;
      this.diagnosis_result = ''
      this.disposal_suggestions = ''
      this.disposal_result = ''
      this.step_list = []
      this.task_insert_params = {}
      this.createTask(this.formData)
     
    },
    okDisposal(){
      this.updateDiagnosisResult()

    },
    sendOrder(){
      // this.$message.success('派发处置工单')

      this.$message({
            message: '派发处置工单',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
    },
    cancel(){
      this.$refs.myDialog.close();
    },
    getSelectedRecords() {
      let selectedRows = this.$refs.table.selection;
      console.log('Selected Records:', selectedRows);
      return selectedRows
    },
    modelPipeline(){
      this.$message.success('开发中：根据故障类型和描述，调用故障诊断模型服务，进行自动编排诊断操作')
    },
    executeDiag(){
      debugger
      if(this.running && !this.exeFinished){
        this.running = false
        return
      }

      this.exeFinishedCount = 0;
      this.exeCount = 0;
      this.exeFinished = false;
      this.failItem = null;
      this.diagnosis_result = ''
      this.disposal_suggestions = ''

      let sel_row = this.getSelectedRecords()
      if(!sel_row||sel_row.length==0){
        return 
      }
    
      this.running = true
      let count = this.exeNum = sel_row.length;
      for(let i=0;i<count;i++){
        let item = sel_row[i]
        item.progress = 0;
        item.diagnosis_result = '';
        item.disposal_suggestions_tip = '';
      }
      let randNum =  this.getRandomNum(0,count-1);

      for(let i=0;i<count;i++){
        let item = sel_row[i]
        this.simulateExecution(item,randNum==i)
      }
    },
    stopExecution(){
      if(!this.running){
        return
      }
      this.running = false
     
      while (this.executionTimeoutList.length > 0) {
        const item = this.executionTimeoutList.shift();
        try{
          clearTimeout(item);
        }catch(e){}
      }
    },
    getRandomNum (Min, Max){
          const Range = Max - Min + 1;
          const Rand = Math.random();
          return Min + Math.floor(Rand * Range);
      },
    /**
     * 模拟执行
     */
    simulateExecution(item,isfail) {
      debugger
      const interval = 100; // 时间间隔，单位毫秒
      const totalTime = this.getRandomNum(5000,20000); // 总执行时间，单位毫秒
      const steps = totalTime / interval;

      const failStep = this.getRandomNum(25,steps-10);
      
      let currentStep = 0;
      const increment = 100 / steps;
      item.progress = 0
      let executionTimeout
      const updateProgress = () => {
        if(isfail&&currentStep>=failStep){
          item.diagnosis_result='不通过'
          item.disposal_suggestions_tip = item.disposal_suggestions
          if(executionTimeout){
            clearTimeout(executionTimeout);
          }
          this.exeFinishedCount++
          if(this.exeFinishedCount>=this.exeNum){
            this.exeFinishedFun()
          }
          this.failItem = item;
          this.diagnosis_result = '"'+item.processor_name + '":不通过'
          this.disposal_suggestions = item.disposal_suggestions
          return
        }
        if (currentStep < steps) {
          item.progress += increment;
          currentStep++;
          executionTimeout = setTimeout(updateProgress, interval);
          this.executionTimeoutList.push(executionTimeout)
        } else {
          item.progress = 100; // Ensure progress reaches 100
          item.diagnosis_result='通过'
          this.exeFinishedCount++
          if(this.exeFinishedCount>=this.exeNum){
              this.exeFinishedFun()
          }
        }
      };
      executionTimeout = setTimeout(updateProgress, interval);
      this.executionTimeoutList.push(executionTimeout)
    },
    formatProgress(progress) {
      return parseInt((progress).toFixed(0));
    },
    exeFinishedFun(){
      this.exeFinished = true
      this.updateDiagnosisStatus()
    },
    getProgressStatus(progress) {
      if (progress >= 99) {
        return 'success';
      } else {
        return '';
      }
    },
    updateDiagnosisStatus(){
      let url = '/api/system/DataInterface/457600254498309189/Actions/Call'
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "id", "value": this.formData.f_id
              },
              {
                  "field": "diagnosis_status", "value": "已诊断"
              },
              {
                  "field": "diagnosis_result", "value": this.failItem?('"'+this.failItem.processor_name + '":不通过'):"未检查到问题"
              },
              {
                  "field": "disposal_suggestions", "value": this.failItem?(this.failItem.disposal_suggestions):""
              }
          ]
      }
      request(
        {
          url: url,
          method: 'post',
          data:params
        }).then(res => {

        }).catch(res=>{

        })

    },
    updateDiagnosisResult(){
      /**
       * 更新故障工单的处置结果
       */
      let url = '/api/system/DataInterface/457603278822179909/Actions/Call'
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "id", "value": this.formData.f_id
              },
              {
                  "field": "diagnosis_status", "value": "已诊断"
              },
              {
                  "field": "dispose_status", "value": "已处置"
              },
              {
                  "field": "diagnosis_result", "value": this.failItem?('"'+this.failItem.processor_name + '":不通过'):"未检查到问题"
              },
              {
                  "field": "disposal_suggestions", "value": this.failItem?(this.failItem.disposal_suggestions):""
              },
              {
                  "field": "disposal_result", "value": this.disposal_result
              }
          ]
      }
      request(
        {
          url: url,
          method: 'post',
          data:params
        }).then(res => {
          this.$message({
            message: '故障处置完成，本次处置将存入故障知识库中，为后续机器学习自动化故障诊断提供数据',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
        }).catch(res=>{

        })

    },
    createTask(data){
      debugger
      let sel_taskinfo_url = '/api/system/DataInterface/455255245669269509/Actions/Call'
      let sel_taskstepinfo_url = '/api/system/DataInterface/455266965334786053/Actions/Call'
      let insert_task_url = '/api/system/DataInterface/455219848255897605/Actions/Call'
      let insert_task_step_url = '/api/system/DataInterface/455245488073998341/Actions/Call'
      debugger
      let fault_record_id = data.f_id
      let fault_code = data.fault_code
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "fault_record_id", "value": fault_record_id
              },
              {
                  "field": "fault_code", "value": fault_code
              }
          ]
      }
      
      request(
        {
          url: sel_taskinfo_url,
          method: 'post',
          data:params
        }).then(res => {
          // console.log(res)
          let item = res.code == 200 && res.data && res.data.data && res.data.data.length > 0 ? res.data.data[0] : null
          if (item) {
              this.faultinfo = item
              let { fault_params, fault_name, node_code, pipeline_id, node_name,fault_desc, processors } = item
              let json_processors = JSON.parse(processors)
              let step_count = json_processors.length
              debugger
              params = {
                  "tenant_id": "",
                  "paramList": [
                      {
                          "field": "processor_codes", "value": processors.replace('[', '').replace(']', '')
                      }
                  ]
              }

              request(
                {
                  url: sel_taskstepinfo_url,
                  method: 'post',
                  data:params
                }
              ).then(res2 => {
                  debugger
                  let items = res2.code == 200 && res2.data && res2.data.data && res2.data.data.length > 0 ? res2.data.data : []
                  if (items.length > 0) {
                      let task_id = this.hlsz.guid()
                      this.task_insert_params = {
                          "tenant_id": "",
                          "paramList": [
                              {
                                  "field": "id", "value": task_id
                              },
                              {
                                  "field": "fault_record_id", "value": fault_record_id
                              }
                              , {
                                  "field": "pipeline_id", "value": pipeline_id
                              }
                              ,
                              {
                                  "field": "node_code", "value": node_code
                              }, {

                                  "field": "node_name", "value": node_name
                              }, {
                                  "field": "fault_code", "value": fault_code
                              }, {
                                  "field": "fault_name", "value": fault_name
                              }
                              , {
                                  "field": "params", "value": fault_params
                              }
                              , {
                                  "field": "status", "value": "running"
                              }
                              , {
                                  "field": "step_count", "value": step_count
                              }, {
                                  "field": "step_current", "value": 1
                              }
                          ]
                      }
                      debugger
                      json_processors.forEach((value,index)=>{
                          // console.log(value,index)
                          for (let i = 0; i < items.length; i++) {
                            let item2 = items[i]
                            let { processor_code } = item2
                            if(processor_code==value){
                              item2.step = this.step_list.length+1
                              item2.progress=0
                              item2.diagnosis_result=''
                              item2.disposal_suggestions_tip = ''
                              this.step_list.push(item2)
                            }
                          }
                      })

                      this.$nextTick(()=>{
                        debugger
                        this.step_list.forEach(item => {
                          if(item.isoften=='是'){
                            item.selected = true;
                            this.$refs.table.toggleRowSelection(item, true) //指定元素取消选中：ele要取消选中的元素,fasle取消选中,true为选中
                          }
                
                        });
                      })
                  }else{
                    /**
                     * 没有查询到故障诊断编排步骤
                     */
                  }

              }).catch(res2 => {
                  this.$message.error('创建诊断任务步骤信息失败:' + res2)
                  // console.log(res)
                  debugger
              })

          }else{
            /**
             * 没有查询到故障诊断编排
             */

          }
      }).catch(res => {
          // console.log(res)
          this.$message.error('创建诊断任务信息失败:'+res)
          debugger
      })
    },
   
    handleSuccess(res, file) {
      this.btnLoading = false
      debugger
      if (res.code == 200) {
        if(res.data&&res.data.url){
          this.$message({
            message: '导入完成，正在下载错误数据...',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
          this.jnpf.downloadFile(res.data.url)
        }else{
          this.$message({
            message: '导入成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
        }  
      } else {
        this.$message({ message: '导入失败', type: 'error', duration: 1000 })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 40px 30px !important;
  max-height: 100vh  !important;
}
.no-wrap-cell {
  white-space: nowrap;
}
/* 可以根据需要添加自定义样式 */
.progress-container {
  position: relative;
  display: flex;
  align-items: center;
}

.progress-bar {
  flex: 1;
}

.status-icon {
  display: flex;
  align-items: center;
  font-size: 20px;
}

.success-icon {
  margin-left: 10px;
  color: #67c23a;
}
.exception-icon {
  margin-right: 10px;
  color: #f56c6c;
}

.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  margin-right: 10px;
}
.grid-content {
  &:first-child {
    border-right: 1px solid #dcdfe6;
  }

  text-align: center;

  p {
    text-align: center;
  }

  img {
    width: 128px;
    margin: 10px 0;
  }
}
</style>